package com.sluggard.common.utils;

import org.springframework.beans.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Lzhen
 * @Package com.micro.util
 * @date 2023/2/14 15:23
 */
public class BeanTransferUtils<T> {

    public static <T> T transfer(Object obj, Class<T> clazz) {
        if (obj != null && clazz != null) {
            T o = null;

            try {
                o = clazz.getDeclaredConstructor().newInstance();
            } catch (InstantiationException | IllegalAccessException var4) {
                var4.printStackTrace();
            } catch (InvocationTargetException | NoSuchMethodException e) {
                throw new RuntimeException(e);
            }

            BeanUtils.copyProperties(obj, o);
            return o;
        } else {
            return null;
        }
    }

    public static <T> List<T> transferList(List<?> objectList, Class<T> clazz) {
        if (objectList != null && objectList.size() != 0 && clazz != null) {
            ArrayList<T> arrayList = new ArrayList<>();
            objectList.forEach((item) -> {
                arrayList.add(transfer(item, clazz));
            });
            return arrayList;
        } else {
            return null;
        }
    }
}
